package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApCollectionBehaviorMapper;
import com.usian.article.service.ApCollectionBehaviorService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl extends ServiceImpl<ApCollectionBehaviorMapper, ApCollection> implements ApCollectionBehaviorService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        //1.参数校验
        if(dto == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数有误");
        }
        //2.查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数有误");
        }

        //3.保存或更新收藏的行为
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, apBehaviorEntry.getId()).eq(ApCollection::getArticleId, dto.getArticleId()));
        if(apCollection == null){
            apCollection = new ApCollection();
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setType(dto.getType());
            apCollection.setPublishedTime(new Date());
            apCollection.setCollectionTime(new Date());
            save(apCollection);
        }else{
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            updateById(apCollection);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
